import { to } from 'await-to-js';
import { getToken, removeToken, setToken } from '@/utils/auth';
import { getInfo as getUserInfo, login as loginApi, logout as logoutApi, isLoging } from '@/api/login';
import { LoginData } from '@/api/types';
import defAva from '@/assets/images/profile.jpg';
import store from '@/store';
import { defineStore } from 'pinia'
import { ref } from 'vue';

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken());
  const sex = ref('0');
  const name = ref('');
  const nickname = ref('');
  const email = ref('');
  const remark = ref('');
  const postsCount = ref(0);
  const collectSiteCount = ref(0);
  const fishSiteCount = ref(0);
  const userId = ref<string | number>('');
  const tenantId = ref<string>('');
  const avatar = ref('');

  /**
   * 登录
   * @param userInfo
   * @returns
   */
  const login = async (userInfo: LoginData): Promise<void> => {
    const [err, res] = await to(loginApi(userInfo));
    if (res) {
      const data = res.data;
      setToken(data.access_token);
      token.value = data.access_token;
      return Promise.resolve();
    }
    return Promise.reject(err);
  };

  /**
   * 检查用户是否登录 
   * @returns 
   */
  const isLoggedIn = async (): Promise<boolean> => {
    // 校验是否存在token
    if (token.value) {
      return true;
    }
    
    const [err, res] = await to(isLoging());
  
    return false;
  }

  // 获取用户信息
  const getInfo = async (): Promise<void> => {
    const [err, res] = await to(getUserInfo());
    if (res) {
      const user = res.data;
      const profile = user.avatarUrl == '' || user.avatarUrl == null ? defAva : user.avatarUrl;
      name.value = user.username;
      nickname.value = user.nickname;
      sex.value = user.sex;
      avatar.value = profile;
      userId.value = user.userId;
      postsCount.value = user.postsCount;
      collectSiteCount.value = user.collectSiteCount;
      fishSiteCount.value = user.fishSiteCount;
      remark.value = user.remark;
      email.value = user.email;
      return Promise.resolve();
    }
    return Promise.reject(err);
  };


  // 注销
  const logout = async (): Promise<void> => {
    await logoutApi();
    token.value = '';
    removeToken();
    clearUserInfo();
  };

  const clearUserInfo = (): void => {
    userId.value = '';
    tenantId.value = '';
    token.value = '';
    name.value = '';
    nickname.value = '';
    avatar.value = '';
  };

  const setAvatar = (value: string) => {
    avatar.value = value;
  };
  

  return {
    userId,
    tenantId,
    token,
    nickname,
    name,
    avatar,
    postsCount,
    collectSiteCount,
    fishSiteCount,
    sex,
    email,
    remark,
    login,
    getInfo,
    logout,
    setAvatar,
    isLoggedIn,
  };
});

export default useUserStore;
// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
